const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const app = express();

// 环境变量
const NODE_ENV = process.env.NODE_ENV || 'development';
const CLIENT_URL = process.env.CLIENT_URL || (NODE_ENV === 'production' ? '' : 'http://localhost:5173');

// CORS 配置
const corsOptions = {
  origin: NODE_ENV === 'production' 
    ? false // 生产环境不设置 origin，由同源策略处理
    : ['http://localhost:5173', 'http://localhost:3000', '*'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
};

app.use(cors(corsOptions));
app.use(express.json());

// 生产环境：提供静态文件服务
if (NODE_ENV === 'production') {
  const clientDistPath = path.join(__dirname, '../client/dist');
  app.use(express.static(clientDistPath));
  
  // SPA 路由回退：所有非 API 路由都返回 index.html
  app.get('*', (req, res, next) => {
    // 排除 API 路由
    if (req.path.startsWith('/api') || req.path.startsWith('/socket.io')) {
      return next();
    }
    res.sendFile(path.join(clientDistPath, 'index.html'));
  });
}

const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: NODE_ENV === 'production' 
            ? false // 生产环境同源，不需要 CORS
            : ['http://localhost:5173', 'http://localhost:3000', '*'],
        methods: ["GET", "POST"],
        credentials: true
    }
});

// 游戏配置
const ROLES = {
    GOOD: ['梅林', '派西维尔', '忠臣', '忠臣', '忠臣'],
    EVIL: ['莫德雷德', '刺客', '爪牙']
};

const PLAYER_COUNTS = {
    5: { good: 3, evil: 2, quests: [2, 3, 2, 3, 3] },
    6: { good: 4, evil: 2, quests: [2, 3, 4, 3, 4] },
    7: { good: 4, evil: 3, quests: [2, 3, 3, 4, 4] },
    8: { good: 5, evil: 3, quests: [3, 4, 4, 5, 5] },
    9: { good: 6, evil: 3, quests: [3, 4, 4, 5, 5] },
    10: { good: 6, evil: 4, quests: [3, 4, 4, 5, 5] }
};

// 房间管理
const rooms = new Map();

// 游戏历史记录管理
const gameHistory = [];
const MAX_HISTORY_SIZE = 100; // 最多保存100条历史记录

// 保存游戏历史记录
function saveGameHistory(room) {
    const historyRecord = {
        id: uuidv4(),
        roomId: room.id,
        timestamp: new Date().toISOString(),
        playerCount: room.players.size,
        players: Array.from(room.players.values()).map(p => ({
            id: p.id,
            name: p.name,
            role: p.role
        })),
        questResults: room.questResults,
        successCount: room.questResults.filter(r => r === true).length,
        failCount: room.questResults.filter(r => r === false).length,
        winner: room.questResults.filter(r => r === true).length >= 3 ? 'good' : 'evil',
        duration: null // 可以计算游戏时长
    };
    
    // 添加到历史记录数组的开头（最新的在前面）
    gameHistory.unshift(historyRecord);
    
    // 如果超过最大数量，删除最旧的记录
    if (gameHistory.length > MAX_HISTORY_SIZE) {
        gameHistory.pop();
    }
    
    return historyRecord;
}

// 获取游戏历史记录
function getGameHistory(limit = 50) {
    return gameHistory.slice(0, limit);
}

class Room {
    constructor(id, host) {
        this.id = id;
        this.host = host;
        this.players = new Map();
        this.gameState = 'waiting'; // waiting, playing, finished
        this.currentQuest = 0; // 当前任务轮次 0-4
        this.currentRound = 0; // 当前任务的第几轮投票 0-4
        this.questResults = [];
        this.leaderIndex = 0; // 当前队长索引
        this.playerOrder = []; // 固定的玩家ID顺序，用于确定队长
        this.votes = new Map(); // 任务队伍投票 {socketId: true/false}
        this.questVotes = new Map(); // 任务投票 {socketId: true/false}
        this.roles = [];
        this.requiredPlayerCount = null;
        this.phase = 'selectLeader'; // selectLeader, selectTeam, voteTeam, voteLaunch, voteQuest, questResult, assassination
        this.launchVotes = new Map(); // 发车投票
        this.selectedTeam = []; // 当前选中的任务队伍 [socketId1, socketId2, ...]
        this.voteRound = 0; // 当前任务队伍投票轮次
        this.maxVoteRounds = 5; // 最多5轮投票
        this.assassinationTarget = null; // 刺客选择的刺杀目标
    }

    addPlayer(socketId, playerName) {
        if (this.players.has(socketId)) return false;

        // 确定最大允许人数：如果设置了requiredPlayerCount，使用它；否则使用10
        const maxPlayers = this.requiredPlayerCount || 10;

        // 如果设置了所需人数，检查是否已达到
        if (this.players.size >= maxPlayers) {
            return false;
        }

        this.players.set(socketId, {
            id: socketId,
            name: playerName,
            role: null,
            isReady: false
        });
        return true;
    }

    removePlayer(socketId) {
        this.players.delete(socketId);
        if (this.players.size === 0) {
            rooms.delete(this.id);
        } else if (this.host === socketId && this.players.size > 0) {
            this.host = Array.from(this.players.keys())[0];
        }
    }

    setRequiredPlayerCount(count) {
        if (count < 5 || count > 10) return false;
        this.requiredPlayerCount = count;
        return true;
    }

    startGame() {
        const playerCount = this.players.size;

        // 如果设置了所需人数，必须达到该人数
        if (this.requiredPlayerCount) {
            if (playerCount !== this.requiredPlayerCount) {
                return false;
            }
        } else {
            // 如果没有设置，使用默认规则
            if (playerCount < 5 || playerCount > 10) return false;
        }

        const config = PLAYER_COUNTS[playerCount];
        const players = Array.from(this.players.values());

        // 分配角色
        const roles = [];
        for (let i = 0; i < config.good; i++) {
            roles.push(ROLES.GOOD[i] || '忠臣');
        }
        for (let i = 0; i < config.evil; i++) {
            roles.push(ROLES.EVIL[i]);
        }

        // 随机分配角色
        for (let i = roles.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [roles[i], roles[j]] = [roles[j], roles[i]];
        }

        // 设置角色
        let roleIndex = 0;
        this.roles = [];
        players.forEach(player => {
            const role = roles[roleIndex++];
            player.role = role;
            this.roles.push(role);
        });

        this.gameState = 'playing';
        this.currentQuest = 0;
        this.currentRound = 0;
        this.questResults = [];
        // 保存游戏开始时的玩家ID顺序，用于确定队长
        this.playerOrder = Array.from(this.players.keys());
        this.leaderIndex = 0;
        this.votes.clear();
        this.questVotes.clear();
        this.selectedTeam = [];
        this.phase = 'selectLeader';
        this.voteRound = 0;

        return true;
    }

    // 重置游戏（准备下一局）
    resetGame() {
        // 重置游戏状态
        this.gameState = 'waiting';
        this.currentQuest = 0;
        this.currentRound = 0;
        this.questResults = [];
        this.playerOrder = [];
        this.leaderIndex = 0;
        this.votes.clear();
        this.questVotes.clear();
        this.launchVotes.clear();
        this.selectedTeam = [];
        this.phase = 'selectLeader';
        this.voteRound = 0;
        this.assassinationTarget = null;

        // 清除所有玩家的角色和准备状态
        this.players.forEach(player => {
            player.role = null;
            player.isReady = false;
        });

        this.roles = [];

        return true;
    }

    // 获取当前队长
    getCurrentLeader() {
        // 使用固定的玩家顺序，确保队长ID正确
        if (!this.playerOrder || this.playerOrder.length === 0) {
            // 如果playerOrder未初始化，使用当前玩家列表（兼容旧逻辑）
            const players = Array.from(this.players.keys());
            return players[this.leaderIndex] || null;
        }
        
        // 确保leaderIndex在有效范围内
        const validIndex = this.leaderIndex % this.playerOrder.length;
        const leaderId = this.playerOrder[validIndex];
        
        // 验证该玩家是否仍在游戏中
        if (this.players.has(leaderId)) {
            return leaderId;
        }
        
        // 如果队长已离开，找到下一个有效玩家
        for (let i = 0; i < this.playerOrder.length; i++) {
            const index = (this.leaderIndex + i) % this.playerOrder.length;
            const playerId = this.playerOrder[index];
            if (this.players.has(playerId)) {
                this.leaderIndex = index;
                return playerId;
            }
        }
        
        // 如果所有玩家都离开了，返回null
        return null;
    }

    // 选择任务队伍（队长选择队员，自动发起投票）
    selectTeam(leaderId, team) {
        // 如果phase是selectLeader，进入selectTeam阶段
        if (this.phase === 'selectLeader') {
            if (this.getCurrentLeader() !== leaderId) return false;
            this.phase = 'selectTeam';
        } else if (this.phase !== 'selectTeam') {
            return false;
        }
        if (this.getCurrentLeader() !== leaderId) return false;

        const config = PLAYER_COUNTS[this.players.size];
        const requiredCount = config.quests[this.currentQuest];

        if (team.length !== requiredCount) return false;

        // 验证队员都是有效玩家
        for (const playerId of team) {
            if (!this.players.has(playerId)) return false;
        }

        // 保存选择的队伍，并自动发起投票
        this.selectedTeam = team;
        this.votes.clear();
        this.phase = 'voteTeam';
        this.voteRound++;
        return true;
    }

    // 队长发起投票
    launchTeamVote(leaderId) {
        if (this.phase !== 'selectTeam') return false;
        if (this.getCurrentLeader() !== leaderId) return false;
        if (this.selectedTeam.length === 0) return false;

        const config = PLAYER_COUNTS[this.players.size];
        const requiredCount = config.quests[this.currentQuest];

        if (this.selectedTeam.length !== requiredCount) return false;

        // 发起投票，进入投票阶段
        this.votes.clear();
        this.phase = 'voteTeam';
        this.voteRound++;
        return true;
    }

    // 投票表决任务队伍（是否同意队长的选择）
    voteForTeam(socketId, approve) {
        if (this.phase !== 'voteTeam') return { success: false, gameEnd: null };
        if (this.votes.has(socketId)) return { success: false, gameEnd: null };

        this.votes.set(socketId, approve);

        // 如果所有人都投票了
        if (this.votes.size === this.players.size) {
            const approveCount = Array.from(this.votes.values()).filter(v => v).length;
            const rejectCount = this.players.size - approveCount;

            if (approveCount > rejectCount) {
                // 队伍投票通过，小队成立，直接进入任务投票阶段
                // 投票成功，重置投票轮次（为下个任务做准备）
                this.voteRound = 0;
                this.phase = 'voteQuest';
                this.questVotes.clear();
                return { success: true, gameEnd: null };
            } else {
                // 拒绝，队长失败，换下一个队长
                this.voteRound++;
                
                if (this.voteRound >= this.maxVoteRounds) {
                    // 连续5次提名失败，坏人直接获胜
                    this.questResults.push(false);
                    // 坏人胜利（5次投票失败）
                    this.phase = 'finished';
                    this.gameState = 'finished';
                    return { success: true, gameEnd: 'evil' };
                } else {
                    // 下一轮队长（按顺序轮流）
                    if (this.playerOrder && this.playerOrder.length > 0) {
                        // 找到下一个有效玩家（按顺序循环）
                        let found = false;
                        for (let i = 1; i <= this.playerOrder.length; i++) {
                            const nextIndex = (this.leaderIndex + i) % this.playerOrder.length;
                            const nextPlayerId = this.playerOrder[nextIndex];
                            if (this.players.has(nextPlayerId)) {
                                this.leaderIndex = nextIndex;
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // 如果所有玩家都离开了，使用降级方案
                            const playerIds = Array.from(this.players.keys());
                            if (playerIds.length > 0) {
                                this.leaderIndex = 0;
                            }
                        }
                    } else {
                        // 降级方案：使用当前玩家列表
                        const playerIds = Array.from(this.players.keys());
                        if (playerIds.length > 0) {
                            this.leaderIndex = (this.leaderIndex + 1) % playerIds.length;
                        }
                    }
                    this.phase = 'selectLeader';
                    this.selectedTeam = [];
                    this.votes.clear();
                    return { success: true, gameEnd: null };
                }
            }
        }
        // 投票成功，但还没所有人投票
        return { success: true, gameEnd: null };
    }

    // 发车投票（任务队员投票是否发车）
    voteForLaunch(socketId, launch) {
        if (this.phase !== 'voteLaunch') return { success: false, gameEnd: null };
        if (!this.selectedTeam.includes(socketId)) return { success: false, gameEnd: null }; // 只有任务队员可以投票
        if (this.launchVotes.has(socketId)) return { success: false, gameEnd: null };

        this.launchVotes.set(socketId, launch);

        // 如果所有任务队员都投票了
        if (this.launchVotes.size === this.selectedTeam.length) {
            const launchCount = Array.from(this.launchVotes.values()).filter(v => v).length;
            const notLaunchCount = this.selectedTeam.length - launchCount;

            if (launchCount > notLaunchCount) {
                // 发车投票通过，进入任务投票阶段
                // 发车投票成功，重置投票轮次（为下个任务做准备）
                this.voteRound = 0;
                this.phase = 'voteQuest';
                this.questVotes.clear();
                return { success: true, gameEnd: null };
            } else {
                // 发车投票失败，队长失败，换下一个队长
                this.voteRound++;
                
                if (this.voteRound >= this.maxVoteRounds) {
                    // 连续5次提名失败，坏人直接获胜
                    this.questResults.push(false);
                    // 坏人胜利（5次投票失败）
                    this.phase = 'finished';
                    this.gameState = 'finished';
                    return { success: true, gameEnd: 'evil' };
                } else {
                    // 下一轮队长（按顺序轮流）
                    if (this.playerOrder && this.playerOrder.length > 0) {
                        // 找到下一个有效玩家（按顺序循环）
                        let found = false;
                        for (let i = 1; i <= this.playerOrder.length; i++) {
                            const nextIndex = (this.leaderIndex + i) % this.playerOrder.length;
                            const nextPlayerId = this.playerOrder[nextIndex];
                            if (this.players.has(nextPlayerId)) {
                                this.leaderIndex = nextIndex;
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // 如果所有玩家都离开了，使用降级方案
                            const playerIds = Array.from(this.players.keys());
                            if (playerIds.length > 0) {
                                this.leaderIndex = 0;
                            }
                        }
                    } else {
                        // 降级方案：使用当前玩家列表
                        const playerIds = Array.from(this.players.keys());
                        if (playerIds.length > 0) {
                            this.leaderIndex = (this.leaderIndex + 1) % playerIds.length;
                        }
                    }
                    this.phase = 'selectLeader';
                    this.selectedTeam = [];
                    this.votes.clear();
                    this.launchVotes.clear();
                    return { success: true, gameEnd: null };
                }
            }
        }
        return { success: true, gameEnd: null };
    }

    // 任务投票（成功/失败）
    voteForQuest(socketId, success) {
        if (this.phase !== 'voteQuest') return false;
        if (!this.selectedTeam.includes(socketId)) return false; // 只有任务队员可以投票
        if (this.questVotes.has(socketId)) return false;

        this.questVotes.set(socketId, success);

        // 如果所有任务队员都投票了
        if (this.questVotes.size === this.selectedTeam.length) {
            // 统计失败票数
            const failCount = Array.from(this.questVotes.values()).filter(v => !v).length;
            const playerCount = this.players.size;
            const questIndex = this.currentQuest; // 0-4 对应任务1-5
            
            // 任务失败判定规则：
            // 默认：只要有1张失败票 → 任务失败
            // 特殊情况：某些人数下的第4个任务（第4轮，index 3）需要2张失败票才失败
            // 规则：5人局第4轮、7-10人局第4轮需要2张失败票才失败
            let questSuccess = true;
            
            if (failCount === 0) {
                // 全是成功票 → 任务成功
                questSuccess = true;
            } else if (failCount >= 2) {
                // 2张或以上失败票 → 任务失败
                questSuccess = false;
            } else {
                // 只有1张失败票的情况
                // 默认：1张失败票 → 任务失败
                questSuccess = false;
                
                // 特殊情况：第4个任务（第4轮，index 3）某些人数需要2张失败票才失败
                // 5人局第4轮需要2张失败票
                // 7-10人局第4轮需要2张失败票
                if (questIndex === 3) { // 第4轮（任务4，index 3）
                    if (playerCount === 5 || (playerCount >= 7 && playerCount <= 10)) {
                        // 需要2张失败票才失败，只有1张则成功
                        questSuccess = true;
                    }
                }
            }

            this.questResults.push(questSuccess);
            
            // 检查是否进入刺杀阶段（好人完成3次任务）
            const successCount = this.questResults.filter(r => r === true).length;
            if (successCount >= 3 && this.phase !== 'assassination') {
                // 进入刺杀阶段
                this.phase = 'assassination';
                this.assassinationTarget = null;
                return { success: true, gameEnd: null, assassinationPhase: true };
            }
            
            // 检查游戏是否结束
            const gameEndResult = this.checkGameEnd();
            if (gameEndResult) {
                // 游戏直接结束（坏人3次失败）
                return { success: true, gameEnd: gameEndResult };
            }
            
            // 继续下一个任务
            const nextQuestResult = this.nextQuest();
            return { success: true, gameEnd: nextQuestResult };
        }
        return { success: true, gameEnd: null };
    }

    // 检查游戏是否结束
    checkGameEnd() {
        if (this.gameState !== 'playing') return null;

        const successCount = this.questResults.filter(r => r === true).length;
        const failCount = this.questResults.filter(r => r === false).length;

        // 坏人胜利：3个任务失败
        if (failCount >= 3) {
            this.phase = 'finished';
            this.gameState = 'finished';
            return 'evil'; // 坏人胜利
        }

        // 好人胜利：3个任务成功 → 进入刺杀阶段（不是直接结束）
        if (successCount >= 3) {
            // 如果还没进入刺杀阶段，则进入刺杀阶段
            if (this.phase !== 'assassination') {
                this.phase = 'assassination';
                this.assassinationTarget = null;
                return null; // 返回null表示进入刺杀阶段，游戏未结束
            }
            // 如果已经在刺杀阶段，说明刺杀已完成，游戏结束
            // 这个逻辑在assassinate方法中处理
            return null;
        }

        // 如果5个任务都完成了，根据结果判断
        if (this.currentQuest >= 5 && this.questResults.length >= 5) {
            if (successCount >= 3) {
                // 好人3次任务成功，进入刺杀阶段
                if (this.phase !== 'assassination') {
                    this.phase = 'assassination';
                    this.assassinationTarget = null;
                    return null;
                }
            } else {
                // 坏人3次任务失败，直接获胜
                this.phase = 'finished';
                this.gameState = 'finished';
                return 'evil';
            }
        }

        return null; // 游戏未结束
    }

    // 获取刺客玩家ID
    getAssassin() {
        for (const [playerId, player] of this.players.entries()) {
            if (player.role === '刺客') {
                return playerId;
            }
        }
        return null;
    }

    // 获取梅林玩家ID
    getMerlin() {
        for (const [playerId, player] of this.players.entries()) {
            if (player.role === '梅林') {
                return playerId;
            }
        }
        return null;
    }

    // 刺客刺杀梅林
    assassinate(assassinId, targetPlayerId) {
        if (this.phase !== 'assassination') return { success: false, gameEnd: null };
        
        // 检查是否是刺客
        const assassin = this.players.get(assassinId);
        if (!assassin || assassin.role !== '刺客') {
            return { success: false, gameEnd: null };
        }

        // 检查目标玩家是否存在
        if (!this.players.has(targetPlayerId)) {
            return { success: false, gameEnd: null };
        }

        // 记录刺杀目标
        this.assassinationTarget = targetPlayerId;

        // 获取梅林玩家ID
        const merlinId = this.getMerlin();

        // 判断刺杀结果
        let gameEndResult = null;
        if (targetPlayerId === merlinId) {
            // 猜对了（选中真梅林）→ 坏人获胜
            this.phase = 'finished';
            this.gameState = 'finished';
            gameEndResult = 'evil';
        } else {
            // 猜错了 → 好人获胜
            this.phase = 'finished';
            this.gameState = 'finished';
            gameEndResult = 'good';
        }

        return { success: true, gameEnd: gameEndResult };
    }

    // 进入下一个任务
    nextQuest() {
        this.currentQuest++;
        this.currentRound = 0;
        this.voteRound = 0;
        
        // 新任务的队长：使用playerOrder循环
        if (this.playerOrder && this.playerOrder.length > 0) {
            this.leaderIndex = this.currentQuest % this.playerOrder.length;
            // 确保队长仍在游戏中
            if (!this.players.has(this.playerOrder[this.leaderIndex])) {
                // 如果队长已离开，找到下一个有效玩家
                for (let i = 0; i < this.playerOrder.length; i++) {
                    const index = (this.currentQuest + i) % this.playerOrder.length;
                    if (this.players.has(this.playerOrder[index])) {
                        this.leaderIndex = index;
                        break;
                    }
                }
            }
        } else {
            // 降级方案：使用当前玩家数量
            this.leaderIndex = this.currentQuest % this.players.size;
        }

        // 检查游戏是否结束
        const gameEndResult = this.checkGameEnd();
        if (gameEndResult) {
            // 游戏结束，将在任务完成时发送游戏结束事件
            return gameEndResult;
        }

        if (this.currentQuest >= 5) {
            // 游戏结束（所有任务完成）
            this.phase = 'finished';
            this.gameState = 'finished';
        } else {
            // 下一轮任务
            this.phase = 'selectLeader';
            this.selectedTeam = [];
            this.votes.clear();
            this.launchVotes.clear();
            this.questVotes.clear();
        }

        return null;
    }

    getPublicState(currentPlayerId = null) {
        // 获取当前队长ID
        const currentLeaderId = this.getCurrentLeader();
        
        const players = Array.from(this.players.values()).map(p => ({
            id: p.id,
            name: p.name,
            isReady: p.isReady,
            role: this.gameState === 'playing' ? p.role : null,
            isLeader: p.id === currentLeaderId // 添加是否为队长的标记
        }));

        // 构建投票详情（每个玩家的投票选择）
        const teamVotes = {};
        for (const [playerId, vote] of this.votes.entries()) {
            const player = this.players.get(playerId);
            if (player) {
                teamVotes[playerId] = {
                    playerId,
                    playerName: player.name,
                    vote: vote // true = 同意, false = 拒绝
                };
            }
        }

        const launchVotes = {};
        for (const [playerId, vote] of this.launchVotes.entries()) {
            const player = this.players.get(playerId);
            if (player) {
                launchVotes[playerId] = {
                    playerId,
                    playerName: player.name,
                    vote: vote // true = 发车, false = 不发车
                };
            }
        }

        const questVotes = {};
        for (const [playerId, vote] of this.questVotes.entries()) {
            const player = this.players.get(playerId);
            if (player) {
                questVotes[playerId] = {
                    playerId,
                    playerName: player.name,
                    vote: vote // true = 成功, false = 失败
                };
            }
        }

        const state = {
            id: this.id,
            host: this.host,
            players,
            gameState: this.gameState,
            currentQuest: this.currentQuest,
            currentRound: this.currentRound,
            questResults: this.questResults,
            leaderIndex: this.leaderIndex,
            currentLeaderId: currentLeaderId, // 直接返回队长ID（注意：这是getCurrentLeader()的结果）
            requiredPlayerCount: this.requiredPlayerCount,
            phase: this.phase,
            selectedTeam: this.selectedTeam,
            voteRound: this.voteRound,
            votesCount: this.votes.size,
            launchVotesCount: this.launchVotes.size,
            questVotesCount: this.questVotes.size,
            totalPlayers: this.players.size,
            teamSize: this.selectedTeam.length,
            // 添加当前玩家的投票状态
            hasVoted: currentPlayerId ? this.votes.has(currentPlayerId) : false,
            hasLaunchVoted: currentPlayerId ? this.launchVotes.has(currentPlayerId) : false,
            hasQuestVoted: currentPlayerId ? this.questVotes.has(currentPlayerId) : false,
            // 添加投票详情
            teamVotes: teamVotes,
            launchVotes: launchVotes,
            questVotes: questVotes
        };

        // 如果设置了人数，生成角色配置
        if (this.requiredPlayerCount && PLAYER_COUNTS[this.requiredPlayerCount]) {
            const config = PLAYER_COUNTS[this.requiredPlayerCount];
            const roleConfig = {
                goodCount: config.good,
                evilCount: config.evil,
                goodRoles: [],
                evilRoles: []
            };

            let goodIndex = 0;
            let evilIndex = 0;
            for (let i = 0; i < config.good; i++) {
                roleConfig.goodRoles.push(ROLES.GOOD[goodIndex] || '忠臣');
                goodIndex++;
            }
            for (let i = 0; i < config.evil; i++) {
                roleConfig.evilRoles.push(ROLES.EVIL[evilIndex]);
                evilIndex++;
            }
            state.roleConfig = roleConfig;
        }

        return state;
    }

    getPlayerRole(socketId) {
        const player = this.players.get(socketId);
        if (!player) return null;

        const playerIndex = Array.from(this.players.keys()).indexOf(socketId);
        const role = player.role;
        const players = Array.from(this.players.values());

        // 梅林能看到所有坏人（除了莫德雷德）
        if (role === '梅林') {
            const evilPlayers = players
                .map((p, i) => ({ ...p, index: i }))
                .filter(p => ['莫德雷德', '刺客', '爪牙'].includes(p.role));
            return { role, evilPlayers: evilPlayers.filter(p => p.role !== '莫德雷德') };
        }

        // 派西维尔能看到梅林和莫德雷德
        if (role === '派西维尔') {
            const merlin = players.findIndex(p => p.role === '梅林');
            const morgana = players.findIndex(p => p.role === '莫德雷德');
            return { role, merlinIndex: merlin, morganaIndex: morgana };
        }

        // 坏人能看到其他坏人（莫德雷德除外）
        if (['莫德雷德', '刺客', '爪牙'].includes(role)) {
            const evilPlayers = players
                .map((p, i) => ({ ...p, index: i }))
                .filter(p => ['莫德雷德', '刺客', '爪牙'].includes(p.role) && p.id !== socketId);
            return { role, evilPlayers };
        }

        // 忠臣只能看到自己的角色
        return { role };
    }
}

// Socket连接处理
io.on('connection', (socket) => {
    console.log('用户连接:', socket.id);

    // 创建房间
    socket.on('createRoom', (playerName) => {
        const roomId = uuidv4().substring(0, 6).toUpperCase();
        const room = new Room(roomId, socket.id);
        room.addPlayer(socket.id, playerName);
        // 房主自动设置为已准备
        const hostPlayer = room.players.get(socket.id);
        if (hostPlayer) {
            hostPlayer.isReady = true;
        }
        rooms.set(roomId, room);
        socket.join(roomId);
        const publicState = room.getPublicState(socket.id);
        publicState.currentPlayerId = socket.id;
        socket.emit('roomCreated', { roomId, room: publicState });
        console.log(`房间创建: ${roomId} by ${playerName}`);
    });

    // 加入房间
    socket.on('joinRoom', ({ roomId, playerName }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('joinRoomError', '房间不存在');
            return;
        }

        if (room.gameState !== 'waiting') {
            socket.emit('joinRoomError', '游戏已开始');
            return;
        }

        // 检查人数限制
        const maxPlayers = room.requiredPlayerCount || 10;
        if (room.players.size >= maxPlayers) {
            socket.emit('joinRoomError', `房间已满（${room.players.size}/${maxPlayers}）`);
            return;
        }

        if (!room.addPlayer(socket.id, playerName)) {
            socket.emit('joinRoomError', '房间已满或用户名已存在');
            return;
        }

        socket.join(roomId);
        const publicState = room.getPublicState(socket.id);
        publicState.currentPlayerId = socket.id;
        socket.emit('joinedRoom', { roomId, room: publicState });
        // 广播时需要为每个玩家设置正确的 currentPlayerId
        room.players.forEach((player, playerId) => {
            const playerState = room.getPublicState(playerId);
            playerState.currentPlayerId = playerId;
            io.to(playerId).emit('roomUpdated', playerState);
        });
        console.log(`${playerName} 加入房间 ${roomId}`);
    });

    // 设置游戏人数
    socket.on('setPlayerCount', ({ roomId, count }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        if (socket.id !== room.host) {
            socket.emit('error', '只有房主可以设置游戏人数');
            return;
        }

        if (room.gameState !== 'waiting') {
            socket.emit('error', '游戏已开始，无法修改人数');
            return;
        }

        if (room.setRequiredPlayerCount(count)) {
            // 如果当前人数超过设置的人数，不允许新玩家加入
            // 但如果已经加入的玩家可以继续留在房间（不会强制踢出）
            const config = PLAYER_COUNTS[count];
            const roleConfig = {
                goodCount: config.good,
                evilCount: config.evil,
                goodRoles: [],
                evilRoles: []
            };

            // 构建角色列表
            let goodIndex = 0;
            let evilIndex = 0;
            for (let i = 0; i < config.good; i++) {
                roleConfig.goodRoles.push(ROLES.GOOD[goodIndex] || '忠臣');
                goodIndex++;
            }
            for (let i = 0; i < config.evil; i++) {
                roleConfig.evilRoles.push(ROLES.EVIL[evilIndex]);
                evilIndex++;
            }

            const updatedState = room.getPublicState(socket.id);
            // 在房间状态中包含角色配置
            updatedState.roleConfig = roleConfig;
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.roleConfig = roleConfig;
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });
            socket.emit('playerCountSet', {
                count,
                room: updatedState,
                roleConfig
            });
        } else {
            socket.emit('error', '人数设置失败，必须是5-10人');
        }
    });

    // 准备游戏
    socket.on('playerReady', ({ roomId }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        const player = room.players.get(socket.id);
        if (player) {
            player.isReady = !player.isReady;
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });
        }
    });

    // 开始游戏
    socket.on('startGame', ({ roomId }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        if (socket.id !== room.host) {
            socket.emit('error', '只有房主可以开始游戏');
            return;
        }

        const result = room.startGame();
        if (result) {
            const players = Array.from(room.players.values());
            players.forEach(player => {
                const roleInfo = room.getPlayerRole(player.id);
                const publicState = room.getPublicState(player.id);
                // 添加当前玩家的 socket.id 到 room 数据中
                publicState.currentPlayerId = player.id;
                io.to(player.id).emit('gameStarted', {
                    room: publicState,
                    roleInfo
                });
            });
            // 广播房间更新（不包含特定玩家信息）
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });
        } else {
            const playerCount = room.players.size;
            const requiredCount = room.requiredPlayerCount;
            if (requiredCount && playerCount !== requiredCount) {
                socket.emit('error', `当前人数为 ${playerCount}，需要 ${requiredCount} 人才能开始游戏`);
            } else {
                socket.emit('error', '游戏开始失败，请检查玩家数量和准备状态');
            }
        }
    });

    // 获取房间信息
    socket.on('getRoom', ({ roomId }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('roomNotFound');
            return;
        }

        const roleInfo = room.getPlayerRole(socket.id);
        const publicState = room.getPublicState(socket.id);
        // 添加当前玩家的 socket.id 到 room 数据中
        publicState.currentPlayerId = socket.id;
        socket.emit('roomInfo', {
            room: publicState,
            roleInfo: room.gameState === 'playing' ? roleInfo : null
        });
    });

    // 队长选择任务队伍（选择队员，但不发起投票）
    socket.on('selectTeam', ({ roomId, team }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        if (room.selectTeam(socket.id, team)) {
            const state = room.getPublicState(socket.id);
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });
            socket.emit('teamSelected', { team: room.selectedTeam });
            // 自动发起投票，通知所有玩家
            io.to(roomId).emit('voteStarted', {
                team: state.selectedTeam,
                leader: state.players.find(p => p.id === socket.id)?.name || '队长'
            });
        } else {
            socket.emit('error', '选择任务队伍失败');
        }
    });

    // 队长发起投票
    socket.on('launchTeamVote', ({ roomId }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        if (room.launchTeamVote(socket.id)) {
            const state = room.getPublicState(socket.id);
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });
            io.to(roomId).emit('voteStarted', {
                team: state.selectedTeam,
                leader: state.players.find(p => p.id === socket.id)?.name || '队长'
            });
        } else {
            socket.emit('error', '发起投票失败');
        }
    });

    // 投票表决任务队伍（是否同意队长的选择）
    socket.on('voteForTeam', ({ roomId, approve }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('error', '房间不存在');
            return;
        }

        const result = room.voteForTeam(socket.id, approve);
        if (result && result.success) {
            const state = room.getPublicState(socket.id);
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });

            // 检查游戏是否结束
            if (result.gameEnd) {
                // 游戏结束，发送游戏结束事件
                const winner = result.gameEnd; // 'good' 或 'evil'
                const allPlayers = Array.from(room.players.values()).map(p => ({
                    id: p.id,
                    name: p.name,
                    role: p.role
                }));
                const successCount = room.questResults.filter(r => r === true).length;
                const failCount = room.questResults.filter(r => r === false).length;
                
                // 保存游戏历史记录
                const historyRecord = saveGameHistory(room);
                
                io.to(roomId).emit('gameFinished', {
                    winner, // 'good' 或 'evil'
                    players: allPlayers,
                    questResults: room.questResults,
                    successCount,
                    failCount,
                    historyId: historyRecord.id
                });
                return;
            }

            // 如果所有人都投票了，系统自动判定小队是否成立
            // 注意：voteForTeam 方法已经自动判定并更新了 phase
            // 这里需要重新获取最新的 state 来检查当前 phase
            const latestState = room.getPublicState(socket.id);
            
            if (latestState.votesCount === latestState.totalPlayers) {
                const approveCount = Array.from(room.votes.values()).filter(v => v).length;
                const rejectCount = latestState.totalPlayers - approveCount;
                const approved = approveCount > rejectCount;
                
                // 构建详细的投票信息
                const voteDetails = Array.from(room.players.entries()).map(([playerId, player]) => ({
                    playerId,
                    playerName: player.name,
                    vote: room.votes.get(playerId) ?? null // 如果还没投票，返回null
                }));

                io.to(roomId).emit('teamVoteResult', {
                    approved,
                    approveCount,
                    rejectCount,
                    voteDetails,
                    newPhase: latestState.phase, // 发送新的阶段信息
                    newLeader: room.getCurrentLeader() // 如果是队长顺延，发送新队长信息
                });
                
                // 如果通过，小队成立，直接进入任务投票阶段
                if (approved && latestState.phase === 'voteQuest') {
                    io.to(roomId).emit('questVoteStarted', {
                        team: latestState.selectedTeam,
                        message: '小队成立！任务队员请投票决定任务成功或失败！'
                    });
                } else if (!approved && latestState.phase === 'selectLeader') {
                    // 如果拒绝，队长已顺延，通知前端
                    io.to(roomId).emit('leaderChanged', {
                        newLeader: room.getCurrentLeader(),
                        voteRound: room.voteRound,
                        message: `队伍投票被拒绝，队长已顺延给下一位玩家`
                    });
                }
            }
        } else {
            // 提供更详细的错误信息
            if (!result) {
                socket.emit('error', '投票失败：未知错误');
            } else if (result.success === false) {
                if (room.phase !== 'voteTeam') {
                    socket.emit('error', '当前阶段不允许投票');
                } else if (room.votes.has(socket.id)) {
                    socket.emit('error', '您已经投票了');
                } else {
                    socket.emit('error', '投票失败');
                }
            } else {
                socket.emit('error', '投票失败');
            }
        }
    });

    // 发车投票（任务队员投票是否发车）
    socket.on('voteForLaunch', ({ roomId, launch }) => {
        const room = rooms.get(roomId);
        if (!room) return;

        const result = room.voteForLaunch(socket.id, launch);
        if (result && result.success) {
            const state = room.getPublicState(socket.id);
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });

            // 检查游戏是否结束
            if (result.gameEnd) {
                // 游戏结束，发送游戏结束事件
                const winner = result.gameEnd; // 'good' 或 'evil'
                const allPlayers = Array.from(room.players.values()).map(p => ({
                    id: p.id,
                    name: p.name,
                    role: p.role
                }));
                const successCount = room.questResults.filter(r => r === true).length;
                const failCount = room.questResults.filter(r => r === false).length;
                
                // 保存游戏历史记录
                const historyRecord = saveGameHistory(room);
                
                io.to(roomId).emit('gameFinished', {
                    winner, // 'good' 或 'evil'
                    players: allPlayers,
                    questResults: room.questResults,
                    successCount,
                    failCount,
                    historyId: historyRecord.id
                });
                return;
            }

            // 如果所有任务队员都投票了，通知结果
            if (state.launchVotesCount === state.teamSize) {
                const launchCount = Array.from(room.launchVotes.values()).filter(v => v).length;
                const notLaunchCount = state.teamSize - launchCount;
                const launched = launchCount > notLaunchCount;
                
                // 构建详细的投票信息
                const voteDetails = room.selectedTeam.map(playerId => {
                    const player = room.players.get(playerId);
                    return {
                        playerId,
                        playerName: player ? player.name : '未知',
                        vote: room.launchVotes.get(playerId) ?? null
                    };
                });

                io.to(roomId).emit('launchVoteResult', {
                    launched,
                    launchCount,
                    notLaunchCount,
                    voteDetails
                });
                
                // 如果通过，进入任务投票阶段
                if (launched && state.phase === 'voteQuest') {
                    io.to(roomId).emit('questVoteStarted', {
                        team: state.selectedTeam
                    });
                }
            }
        } else {
            // 提供更详细的错误信息
            if (!result) {
                socket.emit('error', '发车投票失败：未知错误');
            } else if (result.success === false) {
                if (room.phase !== 'voteLaunch') {
                    socket.emit('error', '当前阶段不允许发车投票');
                } else if (!room.selectedTeam.includes(socket.id)) {
                    socket.emit('error', '只有任务队员可以投票');
                } else if (room.launchVotes.has(socket.id)) {
                    socket.emit('error', '您已经投票了');
                } else {
                    socket.emit('error', '发车投票失败');
                }
            } else {
                socket.emit('error', '发车投票失败');
            }
        }
    });

    // 任务投票（成功/失败）
    socket.on('voteForQuest', ({ roomId, success }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('error', '房间不存在');
            return;
        }

        const result = room.voteForQuest(socket.id, success);
        if (result && result.success) {
            const state = room.getPublicState(socket.id);
            // 为每个玩家单独发送，包含他们的 currentPlayerId
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });

            // 检查游戏是否结束
            if (result.gameEnd) {
                // 游戏结束，发送游戏结束事件
                const winner = result.gameEnd; // 'good' 或 'evil'
                const allPlayers = Array.from(room.players.values()).map(p => ({
                    id: p.id,
                    name: p.name,
                    role: p.role
                }));
                const successCount = room.questResults.filter(r => r === true).length;
                const failCount = room.questResults.filter(r => r === false).length;
                
                // 保存游戏历史记录
                const historyRecord = saveGameHistory(room);
                
                io.to(roomId).emit('gameFinished', {
                    winner, // 'good' 或 'evil'
                    players: allPlayers,
                    questResults: room.questResults,
                    successCount,
                    failCount,
                    historyId: historyRecord.id
                });
                return;
            }

            // 如果所有任务队员都投票了，通知结果
            if (state.questVotesCount === state.teamSize) {
                const failCount = Array.from(room.questVotes.values()).filter(v => !v).length;
                const successCount = state.teamSize - failCount;
                const questSuccess = room.questResults[room.questResults.length - 1];
                
                // 构建详细的投票信息（注意：任务投票可能需要隐藏失败票的具体投票人）
                const voteDetails = room.selectedTeam.map(playerId => {
                    const player = room.players.get(playerId);
                    return {
                        playerId,
                        playerName: player ? player.name : '未知',
                        vote: room.questVotes.get(playerId) ?? null // true = 成功, false = 失败
                    };
                });

                io.to(roomId).emit('questResult', {
                    success: questSuccess,
                    failCount,
                    successCount,
                    questIndex: room.currentQuest - 1,
                    voteDetails
                });

                // 检查是否进入刺杀阶段
                if (result && result.assassinationPhase) {
                    // 进入刺杀阶段，通知所有玩家
                    io.to(roomId).emit('assassinationPhase', {
                        assassin: room.getAssassin(),
                        message: '好人完成了3次任务！刺客可以刺杀梅林了！'
                    });
                } else {
                    // 检查游戏是否结束（任务完成后）
                    const gameEndResult = room.checkGameEnd();
                    if (gameEndResult) {
                        const winner = gameEndResult; // 'good' 或 'evil'
                        const allPlayers = Array.from(room.players.values()).map(p => ({
                            id: p.id,
                            name: p.name,
                            role: p.role
                        }));
                        const successCount = room.questResults.filter(r => r === true).length;
                        const failCount = room.questResults.filter(r => r === false).length;
                        
                        // 保存游戏历史记录
                        const historyRecord = saveGameHistory(room);
                        
                        io.to(roomId).emit('gameFinished', {
                            winner, // 'good' 或 'evil'
                            players: allPlayers,
                            questResults: room.questResults,
                            successCount,
                            failCount,
                            historyId: historyRecord.id
                        });
                    } else if (room.phase === 'assassination') {
                        // 进入刺杀阶段
                        io.to(roomId).emit('assassinationPhase', {
                            assassin: room.getAssassin(),
                            message: '好人完成了3次任务！刺客可以刺杀梅林了！'
                        });
                    }
                }
            }
        } else {
            // 提供更详细的错误信息
            if (!result) {
                socket.emit('error', '任务投票失败：未知错误');
            } else if (result.success === false) {
                if (room.phase !== 'voteQuest') {
                    socket.emit('error', '当前阶段不允许任务投票');
                } else if (!room.selectedTeam.includes(socket.id)) {
                    socket.emit('error', '只有任务队员可以投票');
                } else if (room.questVotes.has(socket.id)) {
                    socket.emit('error', '您已经投票了');
                } else {
                    socket.emit('error', '任务投票失败');
                }
            } else {
                socket.emit('error', '任务投票失败');
            }
        }
    });

    // 刺客刺杀
    socket.on('assassinate', ({ roomId, targetPlayerId }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('error', '房间不存在');
            return;
        }

        const result = room.assassinate(socket.id, targetPlayerId);
        if (result && result.success) {
            // 获取梅林和目标玩家信息
            const merlinId = room.getMerlin();
            const targetPlayer = room.players.get(targetPlayerId);
            const merlinPlayer = merlinId ? room.players.get(merlinId) : null;
            
            const isCorrect = targetPlayerId === merlinId;
            
            // 发送刺杀结果给所有玩家
            io.to(roomId).emit('assassinationResult', {
                isCorrect,
                targetPlayerId,
                targetPlayerName: targetPlayer ? targetPlayer.name : '未知',
                merlinId,
                merlinName: merlinPlayer ? merlinPlayer.name : '未知',
                winner: result.gameEnd
            });

            // 检查游戏是否结束
            if (result.gameEnd) {
                // 游戏结束，发送游戏结束事件
                const winner = result.gameEnd; // 'good' 或 'evil'
                const allPlayers = Array.from(room.players.values()).map(p => ({
                    id: p.id,
                    name: p.name,
                    role: p.role
                }));
                const successCount = room.questResults.filter(r => r === true).length;
                const failCount = room.questResults.filter(r => r === false).length;
                
                // 保存游戏历史记录
                const historyRecord = saveGameHistory(room);
                
                io.to(roomId).emit('gameFinished', {
                    winner, // 'good' 或 'evil'
                    players: allPlayers,
                    questResults: room.questResults,
                    successCount,
                    failCount,
                    assassination: {
                        targetPlayerId,
                        targetPlayerName: targetPlayer ? targetPlayer.name : '未知',
                        merlinId,
                        merlinName: merlinPlayer ? merlinPlayer.name : '未知',
                        isCorrect,
                        winner
                    },
                    historyId: historyRecord.id
                });
            } else {
                // 更新房间状态（虽然不应该发生，但为了安全）
                room.players.forEach((p, playerId) => {
                    const playerState = room.getPublicState(playerId);
                    playerState.currentPlayerId = playerId;
                    io.to(playerId).emit('roomUpdated', playerState);
                });
            }
        } else {
            // 提供更详细的错误信息
            if (!result) {
                socket.emit('error', '刺杀失败：未知错误');
            } else if (result.success === false) {
                if (room.phase !== 'assassination') {
                    socket.emit('error', '当前阶段不允许刺杀');
                } else {
                    const assassin = room.players.get(socket.id);
                    if (!assassin || assassin.role !== '刺客') {
                        socket.emit('error', '只有刺客可以刺杀');
                    } else if (!room.players.has(targetPlayerId)) {
                        socket.emit('error', '目标玩家不存在');
                    } else {
                        socket.emit('error', '刺杀失败');
                    }
                }
            } else {
                socket.emit('error', '刺杀失败');
            }
        }
    });

    // 重置游戏（准备下一局）
    socket.on('resetGame', ({ roomId }) => {
        const room = rooms.get(roomId);
        if (!room) {
            socket.emit('error', '房间不存在');
            return;
        }

        if (socket.id !== room.host) {
            socket.emit('error', '只有房主可以重置游戏');
            return;
        }

        const result = room.resetGame();
        if (result) {
            // 通知所有玩家游戏已重置
            room.players.forEach((p, playerId) => {
                const playerState = room.getPublicState(playerId);
                playerState.currentPlayerId = playerId;
                io.to(playerId).emit('roomUpdated', playerState);
            });

            // 发送游戏重置事件
            io.to(roomId).emit('gameReset', {
                message: '游戏已重置，可以开始新一局游戏'
            });
        } else {
            socket.emit('error', '重置游戏失败');
        }
    });

    // 获取游戏历史记录
    socket.on('getGameHistory', () => {
        const history = getGameHistory(50);
        socket.emit('gameHistory', history);
    });

    // 断开连接
    socket.on('disconnect', () => {
        console.log('用户断开:', socket.id);
        for (const [roomId, room] of rooms.entries()) {
            if (room.players.has(socket.id)) {
                room.removePlayer(socket.id);
                // 广播房间更新（为每个玩家单独发送）
                room.players.forEach((p, playerId) => {
                    const playerState = room.getPublicState(playerId);
                    playerState.currentPlayerId = playerId;
                    io.to(playerId).emit('roomUpdated', playerState);
                });
                break;
            }
        }
    });
});

// HTTP API: 获取游戏历史记录
app.get('/api/game-history', (req, res) => {
    const limit = parseInt(req.query.limit) || 50;
    const history = getGameHistory(limit);
    res.json({
        success: true,
        data: history,
        count: history.length
    });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

